import axios from 'axios';
import { message } from 'antd';
import { store } from '../redux/store';
import { toggleShowLoginModal } from '../redux/actions';

// 创建axios实例
const service = axios.create({
  baseURL: 'http://syt.atguigu.cn',
  timeout: 15000, // 请求超时时间
});

// http request 拦截器
service.interceptors.request.use(
  (config) => {
    // token 先不处理，后续使用时在完善
    const token = store.getState().user.token;
    if (token) {
      config.headers['token'] = token;
    }
    return config;
  },
  (err) => {
    return Promise.reject(err);
  }
);
// http response 拦截器
service.interceptors.response.use(
  (response) => {
    if (response.data.code === 208) {
      store.dispatch(toggleShowLoginModal(true));
      return;
    } else {
      if (response.data.code !== 200) {
        message.error(response.data.message);
        return Promise.reject(response.data);
      } else {
        return response.data.data == null ? response.data : response.data.data;
      }
    }
  },
  (error) => {
    return Promise.reject(error.response);
  }
);
export default service;
